package com.wangshupo.app.webSocket;



import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Component
@ServerEndpoint(value = "/index/hello", configurator = GetHttpSessionConfig.class)   //configurator用于获取HttpSession对象
public class WebSocketService {
    private static final Logger LOG = LoggerFactory.getLogger(WebSocketService.class);

    private static final Map<String, Session> onLineUsers = new ConcurrentHashMap<>();  //定义静态的，所有实例共享,用于存储所有WS会话状态

    private HttpSession httpSession ;

    /**
     * EndpointConfig   取出HttpSession对象
     * @param session
     * @param config
     */
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        //保存httpSession
        this.httpSession = (HttpSession)config.getUserProperties().get(HttpSession.class.getName());
        onLineUsers.put(  (String)httpSession.getAttribute("user"),   session);

        LOG.error("onOpen httpSession={}", this.httpSession);
    }


    //将消息进行 推送（核心逻辑!!）,发送文本消息 session.getBasicRemote().sendText("Hello Client");
    @OnMessage
    public void onMessage(String message, Session session) {
        LOG.error("浏览器发来消息了:{}",message);

        try {
            Session userSession = onLineUsers.get((String) httpSession.getAttribute("user"));
            userSession.getBasicRemote().sendText(message); //发送

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


    @OnClose
    public void onClose(Session session) {
        //移除当前登录用户
        onLineUsers.remove(  (String)httpSession.getAttribute("user")  );
    }

}
